package com.webserver.controllers;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理用户相关业务
 */
@Controller
public class UserController {
    private static String ueserDir ="./users/";
    static{
        File userDir =new File(ueserDir);
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    @RequestMapping("/myweb/regUser")
    public void reg(HttpRequest request, HttpResponse response){
        System.out.println("开始处理用户注册！！！！！！！！！！");
        //1通过request获取用户表单提交的数据
        //获取reg.html中用户名这个输入框的值
        //这里request.getParameter()参数应当与页面上对于输入框的name属性的值
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        String nickname =request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        /**
         * 必要的验证：
         * 要求上述四项信息不能为null；并且年龄还要求必须是一个数字格式
         * 否则直接设置响应对象响应注册失败的提示页面：reg_input_error.html
         * 该页面居中显示一行字：注册失败，输入信息有误
         */
        if(username==null || password==null || nickname==null || ageStr==null||!ageStr.matches("[0-9]+")) {
            File file = new File("./webapps/myweb/reg_input_error.html");
            response.setEntity(file);
            return;
        }
            int age = Integer.parseInt(ageStr);
            System.out.println(username + "," + password + "," + nickname + "," + ageStr);

        /**
         * 判断该用户是否存在，若存在则直接跳转页面：reg_have_user.html
         * 该页面居中显示一行字：该用户已存在，请重新注册
         */
        File userFile =new File(ueserDir + username + ".obj");
        if (userFile.exists()){
            File file =new File("./webapps/myweb/reg_have_user.html");
            response.setEntity(file);
            return;
        }
        //2将该用户写入文件
            try (
                    FileOutputStream fos = new FileOutputStream(userFile);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
            ) {
                User user = new User(username, password, nickname, age);
                oos.writeObject(user);
                //3设置注册成功页面
                File file = new File("./webapps/myweb/reg_success.html");
                response.setEntity(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        //3设置response响应登录结果页面
    }
    @RequestMapping("/myweb/loginUser")
    public void login(HttpRequest request,HttpResponse response){
        System.out.println("开始处理登录！！！！！！");
        String username =request.getParameter("username");
        String password =request.getParameter("password");
        File file =new File("./webapps/myweb/login_fail.html");
        if (username==null || password==null){
            response.setEntity(file);
            return;
        }
        File userFile =new File(ueserDir + username + ".obj");
        if (userFile.exists()){
            try (
                    ObjectInputStream ois =new ObjectInputStream(new FileInputStream(userFile));
                    ) {
                    User user =(User)ois.readObject();
                    if (user.getPassword().equals(password)){
                        File loginSuccess=new File("./webapps/myweb/login_success.html");
                        response.setEntity(loginSuccess);
                        return;
                    }
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
            //登录失败
            response.setEntity(file);

        }
        @RequestMapping("/myweb/showAllUser")
        public void  showAllUser(HttpRequest request,HttpResponse response){
            System.out.println("开始处理显示所有用户");
            //1现将所有用户读取出来
            List<User> userList =new ArrayList<>();//保存所有注册用户的集合
            /**
             * 将users目录下的所有obj文件获取回来，并且进行反序列化User对象，最终将这些User对象全部存入userlist备用
             */
            File dir =new File(ueserDir);
            File[] users =dir.listFiles(f->f.getName().endsWith(".obj"));
                for ( File userFile :users){
                    try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(userFile));) {
                        User user =(User)ois.readObject();
                        userList.add(user);
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            System.out.println(userList);

            //2将用户拼接到一个html的表格中，每个用户拼接一个<tr>

                    PrintWriter pw =response.getWriter();
                    pw.println("<!DOCTYPE html>");
                    pw.println("<html lang=\"en\">");
                    pw.println("<head>");
                    pw.println("<meta charset=\"UTF-8\">");
                    pw.println("<title>用户列表</title>");
                    pw.println("</head>");
                    pw.println("<body>");
                    pw.println("<center>");
                    pw.println("<h1>用户列表</h1>");
                    pw.println("<table border=\"1\">");
                    pw.println("<tr>");
                    pw.println("<td>用户名</td>");
                    pw.println("<td>密码</td>");
                    pw.println("<td>昵称</td>");
                    pw.println("<td>年龄</td>");
                    pw.println("</tr>");
                    for (User user :userList) {
                        pw.println("<tr>");
                        pw.println("<td>"+user.getUsername()+"</td>");
                        pw.println("<td>"+user.getPassword()+"</td>");
                        pw.println("<td>"+user.getNickname()+"</td>");
                        pw.println("<td>"+user.getAge()+"</td>");
                        pw.println("<td>修改 <a href=\"./deleteUser?username="+user.getUsername()+"\">删除</a></td>");
                        pw.println("</tr>");
                    }
                    pw.println("</table>");
                    pw.println("</center>");
                    pw.println("</body>");
                    pw.println("</html>");
                    //拼接页面后，设置响应头
                    response.setContentType("text/html");

            }
    @RequestMapping("/myweb/deleteUser")
    public void deleteUser(HttpRequest request,HttpResponse response){
        String username = request.getParameter("username");

        File userFile = new File(ueserDir + username + ".obj");

        if(userFile.exists()){
            userFile.delete();
            /*
                http://localhost:8088/myweb/deleteUser?username=fancq
                http://localhost:8088/myweb/showAllUser

             */
            //重定向请求显示用户列表
            response.sendRedirect("/myweb/showAllUser");
        }
    }

}
